﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace HealthMonitor.Extensions
{
    public class JsonBinder : IModelBinder
    {
        static readonly Serialization ser = new Serialization();
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            ValueProviderResult value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            if (value == null && bindingContext.ModelType.IsInterface)
                value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + "[0]");
            //if (value == null)
            //      value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".");
            if (value == null)
                return new DefaultModelBinder().BindModel(controllerContext, bindingContext);
            var selected = value.AttemptedValue;

            if (selected == "false")
                return null;


            if (selected.EndsWith(",true", StringComparison.CurrentCultureIgnoreCase) || selected.EndsWith(",false", StringComparison.CurrentCultureIgnoreCase))
                selected = selected.Substring(0, selected.LastIndexOf(','));

            var result = ser.Deserialize(selected, bindingContext.ModelType);
            return result;
        }
    }
}